// pages/detail/detail.js
// 获取数据库数据
const db = wx.cloud.database()
const app = getApp()
import Toast from '../../vant/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDialogLogin: false,
    showBackArrow: true,
    showListInfo: [],
    showBottomPop: false,
    index: {
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 300,
    },
    goodData: {},
    form: {
      _openid: '',
      goodId: '',
      count: 1,
      enable: 1,
      info: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goodId = options.goodId
    // 获取该商品数据
    db.collection('goods_list').where({
      goodId: goodId,
      enable: 1
    })
    .get().then(res => {
      this.setData({
        goodData: res.data[0],
        'form.goodId': goodId
      })
    })
  },
  tapClickBack(e) {
    // wx.switchTab({url: '/pages/index/index'})
    wx.navigateBack({
      delta: 1
    })
  },
  toggleBottomPopup(e) {
    this.setData({
      showBottomPop: !this.data.showBottomPop
    })
  },
  // 点击类别
  tapSelect(e) {
    let target = e.target.dataset
    let index = target.index
    let select = target.select
    let newData = this.data.goodData.goodInfo[index].selection;
    for(let i = 0, len = newData.length; i < len; i ++) {
      newData[i].isChosen = false
    }
    newData[select].isChosen = true
    // 将数据存入form中
    let title = this.data.goodData.goodInfo[index].title;
    this.data.form.info[index] = {}
    this.data.form.info[index]['desc'] = newData[select].desc
    this.data.form.info[index]['title'] = this.data.goodData.goodInfo[index].title
    // 将数据存入form中  -over
    let param = {}
    let string = `goodData.goodInfo[${index}].selection`
    param[string] = newData
    this.setData(param)
  },
  onStepperChange(e) {
    // 步进器change事件
    this.setData({
      'form.count': e.detail
    })
  },
  clickAddCart(e) {
    let openId = app.globalData.openid
    // 点击加入购物车
    let form = this.data.form
    let goodInfo = this.data.goodData.goodInfo
    if(form.info.length < goodInfo.length) {
      // 有的选项没有选择
      Toast.fail('请完成选择')
    } else {
      // 判断是否登录
      if(openId) {
        this.data.form.openId = openId
        app.globalData.openid = openId
        wx.setStorageSync('openId', openId)
        this.data.form.cartId = app.guid()
        // 加入购物车
        wx.cloud.callFunction({
          name: 'addCart',
          data: {form: this.data.form},
          success: res => {
            console.log(res.result)
            Toast.success('成功加入购物车')
            this.setData({
              showBottomPop: false
            })
            // 跳转到购物车页面
            // wx.switchTab({
            //   url: '/pages/car/car'
            // })
          },
          fail: err => {
            Toast.fail('加入购物车失败')
          }
        })
      } else {
        // 用户没有登录
        this.setData({
          showDialogLogin: true
        })
      }
    }
  },
  clickBuy(e) {
    // 点击购买
    let openId = app.globalData.openid
    this.data.form._openid = openId
    this.data.form.goodDetail = this.data.goodData
    // 获取金额
    let priceSum = this.data.form.count * this.data.form.goodDetail.price * 100
    let listData = JSON.stringify([this.data.form])
    wx.navigateTo({
      url: `/pages/order/order?listData=${listData}&priceSum=${priceSum}`
    })
  },
  clickLogin(e) {
    // 存储用户信息
    try {
      wx.setStorageSync('headImgUrl', e.detail.userInfo.avatarUrl)
      wx.setStorageSync('nickName', e.detail.userInfo.nickName)
    } catch (e) {
      Toast.fail('获取信息失败')
    }
    // 获取openId
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        Toast.success('登录成功')
        app.globalData.openid = res.result.openid
        wx.setStorageSync('openId', res.result.openid)
        this.setData({
          showDialogLogin: false
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  clickToCart() {
    // 跳转到购物车页面
    wx.switchTab({
      url: '/pages/car/car'
    })
  }
})